/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* replaceValueInTree(TreeNode* root) {
        vector<TreeNode*>q1;
        q1.push_back(root);
        root->val = 0;
        while (q1.size()) {
            vector<TreeNode*> q2;
            int sum = 0;
            for (auto x : q1) {
                if (x->left) {
                    q2.push_back(x->left);
                    sum += x->left->val;
                }
                if (x->right) {
                    q2.push_back(x->right);
                    sum += x->right->val;
                }
            }
            for (auto x : q1) {
                int ans = 0;
                if (x->left) ans += x->left->val;
                if (x->right) ans += x->right->val;
                if (x->left) x->left->val = sum - ans;
                if (x->right) x->right->val = sum - ans;
            }
            q1 = move(q2);
        }
        return root;
    }
};